package com.lyc.product.servlet;

import com.lyc.product.ServiceImpl.ProductServiceImpl;
import com.lyc.product.bean.Product;
import com.lyc.product.service.ProductService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * Created by Administrator on 2018/12/14.
 */
@WebServlet("/AdminProductServlet")
public class AdminProductServlet extends HttpServlet {
    private ProductService productService = new ProductServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

// Configure a repository (to ensure a secure temp location is used)
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);

// Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

// Parse the request
        try {
            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (item.isFormField()){
                    String name = item.getName();

                }else {
                    InputStream is = item.getInputStream();
//                    ServletContext context = req.getServletContext();
                   OutputStream os = new FileOutputStream(servletContext.getRealPath("/bookImgCover")+"\\"+item.getName());
                    byte[] bytes=new byte[1024];
                    int len;
                   while ((len=is.read(bytes))!=-1){
                             os.write(bytes,0,len);
                    }
                    os.close();
                    is.close();
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }
    protected void getBookByProductId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int productId = 1;
        try {
            productId = Integer.parseInt(req.getParameter("productId"));
        } catch (Exception e) {
        }
        Product bookInfo = productService.getBookByProductId(productId);
        req.setAttribute("bookInfos", bookInfo);
        req.getRequestDispatcher("/adminJsp/adminProduct.jsp").forward(req,resp);
    }
}
